// pages/websocket/socket.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    headWidth: 0,
    bottom: 0,
    windowHeight: "",
    windowWidth: "",
    message: "",
    toUserId: '',
    userId: 0,
    SessionId: '',
    toUserName: '',
    // 头像
    head: {
      self:app.globalData.userinfo.userAvatar,
      server: 'https://img2.baidu.com/it/u=4237756909,3713889849&fm=253&fmt=auto&app=138&f=JPEG?w=400&h=400'
    },
    infoList: [], // 待收集数据信息
    socketOpen: false, // WebSocket连接状态
  },
  // 获取Input框内的数据
  handleChange(opt) {
    this.setData({
      message: opt.detail.value
    })
  },

  focus(e) {
    this.setData({
      // bottom: e.detail.height
      // bottom: app.globalData.StatusBar
    })
  },
  blur(e) {
    this.setData({
      bottom: 0
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this
    this.rollingBottom();
    console.log("options", options);
    this.data.head.server = options.toUserAvatar
    that.setData({
        toUserId: options.id,
        SessionId: options.SessionId,
        windowHeight: getApp().globalData.windowHeight,
        windowWidth: getApp().globalData.windowWidth,
        headWidth: getApp().globalData.CustomBar,
        head: this.data.head,
        toUserName: options.toUsername,
        userId:app.globalData.userinfo.userId
      }),
      this.createSocketServer();
    this.getmsg();

  },
  // 获取历史消息
  getmsg() {
    var that = this
    wx.request({
      url: app.globalData.url + '/msgList?sessionId=' + that.data.SessionId,
      method: "POST",
      header: {
        "authorization": wx.getStorageSync("token")
      },
      success(res) {
        console.log("getmsgres:", res);
        that.setData({
          infoList: res.data.data
        })
        that.rollingBottom();
      },
      fail() {
        wx.showToast({
          title: '还没有登录~',
          icon: 'error'
        })
      },
    })

  },
  createSocketServer() {
    var that = this;
    /**
     * 连接WebSocket服务器
     */
    let userId = app.globalData.userinfo.userId
    wx.connectSocket({
      url: app.globalData.socketUrl + userId + '/' + that.data.SessionId,
      header: {
        'content-type': 'application/json'
      },
    });
    wx.onSocketOpen((result) => {
      console.log("webSocket已连接");
      that.setData({
        socketOpen: true
      })
    });
    wx.onSocketError((result) => {
      console.log('WebSocket连接打开失败:', result)
    });
    wx.onSocketClose(function (res) {
      console.log('WebSocket连接已关闭:', res)
      that.setData({
        socketOpen: false
      })
    });
    wx.onSocketMessage((result) => {
      console.log("收到消息：",JSON.parse(result.data))
      this.data.infoList.push(JSON.parse(result.data));
      this.setData({
        infoList: this.data.infoList,
      })
      
      this.rollingBottom();
    })
  },
  //发消息
  sentMessage() {
    if (!this.data.socketOpen) {
      wx.showToast({
        title: 'WebSocket未连接',
        icon: 'none'
      })
      return
    };
    // 判断消失是否为空
    if (this.data.message == '') {
      wx.showToast({
        title: '消息不能为空',
        icon: 'none'
      })
      return
    };
    this.sendSocketMessage(this.data.message);
    this.setData({
      message: ""
    });
  },
  sendSocketMessage(msg) {
    wx.sendSocketMessage({
      data: msg,
    });
  },
  // 发送按钮
  sentMsg() {
    // 判断消失是否为空
    if (this.data.message == '') {
      wx.showToast({
        title: '消息不能为空',
        icon: 'none'
      })
      return
    };
    this.data.infoList.push({
      id: 1,
      role: 'self',
      content: this.data.message
    });
    this.setData({
      infoList: this.data.infoList
    })
    this.sentMessage();
    this.rollingBottom();

  },
  // 聊天视角调整方法
  rollingBottom() {
    wx.createSelectorQuery().selectAll('.content-list').boundingClientRect(results => {
      this.setData({
        scrollTop: results[0].height
      })
    }).exec()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.closeSocket() // 关闭WebSocket连接
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})